package com.yunmang.DaoUtils;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.yunmang.greendao.gen.DaoMaster;
import com.yunmang.greendao.gen.DaoSession;

import org.greenrobot.greendao.query.QueryBuilder;

/**
 * 封装Daosesiion+DaoMaster+XXdao，并对它们进行初始化
 * Created by ltt on 2017/3/24.
 */
public class DaoManager {
    private static  final String  DB_NAME="BetterForChina.db";//数据库名称
    private volatile  static DaoManager mDaoManager;//多线程访问
    private DaoMaster daoMaster;
    private DaoMaster.DevOpenHelper helper;
    private DaoSession daoSession;
    private SQLiteDatabase db;
    private Context context;

    /**
     * 使用单例模式获取操作数据库的对象
     * @return
     */
    public static DaoManager getInstance(){
        DaoManager instance = null;
        if (mDaoManager==null){
            synchronized (DaoManager.class){
                if (instance==null){
                    instance = new DaoManager();
                    mDaoManager = instance;
                }
            }
        }
        return mDaoManager;
    }

    /**
     * 初始化Context对象
     * @param context
     */
    public void init(Context context){
        this.context = context;
    }

    /**
     * 判断数据库是否存在，不存在则创建
     * @return
     */
    public DaoMaster getDaoMaster(){
        if(daoMaster==null){
            helper=new DaoMaster.DevOpenHelper(context,DB_NAME,null);
            daoMaster=new DaoMaster(helper.getWritableDb());
        }
        return daoMaster;
    }

    /**
     * 获取dao的管理类
     * @return
     */
    public DaoSession getDaoSession(){
        if(daoSession==null){
            if(daoMaster==null){
                getDaoMaster();
            }
            daoSession=daoMaster.newSession();
        }
        return daoSession;
    }

    /**
     * 设置debug模式开启或关闭，默认关闭
     * @param flag
     */
    public void setDebug(boolean flag){
        QueryBuilder.LOG_SQL = flag;
        QueryBuilder.LOG_VALUES = flag;
    }

    /**
     * 关闭数据库
     */
    public void closeDataBase(){
        closeHelper();
        closeDaoSession();
    }

    public void closeDaoSession(){
        if (null != daoSession){
            daoSession.clear();
            daoSession = null;
        }
    }

    public  void  closeHelper(){
        if (helper!=null){
            helper.close();
            helper = null;
        }
    }


}
